﻿namespace ImageProcessing.UI
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    /// <summary>
    /// Morphology form
    /// </summary>
    public partial class IMG_Morphology : Form
    {
        /// <summary>
        /// original image bitmap
        /// </summary>
        private Entities.IMG_Image imgOriginal;

        /// <summary>
        /// Edited image bitmap
        /// </summary>
        private Entities.IMG_Image imgEdited;

        /// <summary>
        /// parent Form referance
        /// </summary>
        private UI.IMG_HomeScreen parentForm;
        
        /// <summary>
        /// origin x
        /// </summary>
        private int orgX;

        /// <summary>
        /// origin y
        /// </summary>
        private int orgY;
        
        /// <summary>
        /// Initializes a new instance of the <see cref="IMG_Morphology"/> class.
        /// </summary>
        /// <param name="img_original">The img_original.</param>
        /// <param name="parent">The parent.</param>
        public IMG_Morphology(Entities.IMG_Image img_original, UI.IMG_HomeScreen parent)
        {
            try
            {
                this.InitializeComponent();
                this.parentForm = parent;
                if (img_original != null)
                {
                    this.imgOriginal = img_original;
                    this.picBoxOriginal.Image = IMG_Processor.IMG_OpenSave.IMG_BufferToBItmap(img_original);
                }
            }
            catch (Exception img_Ex)
            {
                Logger.LogException(img_Ex);
                MessageBox.Show("Error Loading Form");
            }
        }

        /// <summary>
        /// Handles the Click event of the btnOpen control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp; *.ppm)|*.jpg; *.jpeg; *.gif; *.bmp; *.ppm";
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string img_OpenedFilePath = openFileDialog1.FileName;
                    this.imgOriginal = IMG_Processor.IMG_OpenSave.IMG_Open(img_OpenedFilePath);
                    this.picBoxOriginal.Image = IMG_Processor.IMG_OpenSave.IMG_BufferToBItmap(this.imgOriginal);
                    this.imgEdited = null;
                    this.picBoxEdited.Image = null;
                }
            }
            catch
            {
                MessageBox.Show("Error, Can't Open Image");
            }
        }

        /// <summary>
        /// Handles the Click event of the btnApply control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnApply_Click(object sender, EventArgs e)
        {
            if (this.imgOriginal == null)
            {
                MessageBox.Show("Error, must open an image");
                return;
            }

            try
            {
                int img_inputBPP = int.Parse(this.txtThreshold.Text);
                int[,] temp = ImageProcessor.IMG_BinaryImage.ConvertToBinary((this.imgEdited == null ? this.imgOriginal : this.imgEdited), img_inputBPP);
                int[,] mask = new int[int.Parse(this.txtMaskHeight.Text), int.Parse(this.txtMaskWidth.Text)];
                for (int i = 0; i < mask.GetLength(0); i++)
                {
                    for (int j = 0; j < mask.GetLength(1); j++)
                    {
                        mask[i, j] = int.Parse(this.dgvMask[j, i].Value.ToString());
                    }
                }

                this.imgEdited = ImageProcessor.IMG_Morphology.Dilation(temp, mask, this.orgX, this.orgY);
                this.picBoxEdited.Image = IMG_Processor.IMG_OpenSave.IMG_BufferToBItmap(this.imgEdited);
            }
            catch
            {
                MessageBox.Show("Error, Can't Dialate Image");
            }
        }

        /// <summary>
        /// Handles the Click event of the btnMask control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnMask_Click(object sender, EventArgs e)
        {
            try
            {
                this.dgvMask.Rows.Clear();
                this.dgvMask.Columns.Clear();
                int width = int.Parse(this.txtMaskWidth.Text);
                int height = int.Parse(this.txtMaskHeight.Text);
                for (int i = 0; i < width; i++)
                {
                    this.dgvMask.Columns.Add(i.ToString(), string.Empty);
                    for (int j = 0; j < height; j++)
                    {
                        if (i == 0)
                        {
                            this.dgvMask.Rows.Add();
                        }

                        if (this.rdbAllOnes.Checked)
                        {
                            this.dgvMask[i, j].Value = 1;
                        }
                        else
                        {
                            this.dgvMask[i, j].Value = 0;
                        }

                        this.dgvMask.AllowUserToAddRows = false;
                    }
                }

                this.dgvMask.Visible = true;
            }
            catch (Exception img_Ex)
            {
                Logger.LogException(img_Ex);
                MessageBox.Show("Error enter valid values");
            }
        }

        /// <summary>
        /// Handles the CellMouseDoubleClick event of the dgvMask control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DataGridViewCellMouseEventArgs"/> instance containing the event data.</param>
        private void DgvMask_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                this.dgvMask[this.orgX, this.orgY].Style.BackColor = Color.White;
                this.dgvMask[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Red;
                this.orgY = e.RowIndex;
                this.orgX = e.ColumnIndex;
            }
            catch (Exception img_Ex)
            {
                Logger.LogException(img_Ex);
                MessageBox.Show("Error");
            }
        }

        /// <summary>
        /// Handles the CellClick event of the dgvMask control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DataGridViewCellEventArgs"/> instance containing the event data.</param>
        private void DgvMask_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (int.Parse(this.dgvMask[e.ColumnIndex, e.RowIndex].Value.ToString()) == 0)
                {
                    this.dgvMask[e.ColumnIndex, e.RowIndex].Value = 1;
                }
                else
                {
                    this.dgvMask[e.ColumnIndex, e.RowIndex].Value = 0;
                }
            }
            catch (Exception img_Ex)
            {
                Logger.LogException(img_Ex);
                MessageBox.Show("Error ");
            }
        }

        /// <summary>
        /// Handles the Click event of the BtnErusion control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnErusion_Click(object sender, EventArgs e)
        {
            if (this.imgOriginal == null)
            {
                MessageBox.Show("Error, must open an image");
                return;
            }

            try
            {
                int img_inputBPP = int.Parse(this.txtThreshold.Text);
                int[,] temp = ImageProcessor.IMG_BinaryImage.ConvertToBinary((this.imgEdited == null ? this.imgOriginal : this.imgEdited), img_inputBPP);
                int[,] mask = new int[int.Parse(this.txtMaskHeight.Text), int.Parse(this.txtMaskWidth.Text)];
                for (int i = 0; i < mask.GetLength(0); i++)
                {
                    for (int j = 0; j < mask.GetLength(1); j++)
                    {
                        mask[i, j] = int.Parse(this.dgvMask[j, i].Value.ToString());
                    }
                }

                this.imgEdited = ImageProcessor.IMG_Morphology.Erosion(temp, mask, this.orgX, this.orgY);
                this.picBoxEdited.Image = IMG_Processor.IMG_OpenSave.IMG_BufferToBItmap(this.imgEdited);
            }
            catch
            {
                MessageBox.Show("Error, Can't Erude Image");
            }
        }

        /// <summary>
        /// Handles the FormClosing event of the IMG_Morphology control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.FormClosingEventArgs"/> instance containing the event data.</param>
        private void IMG_Morphology_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                this.parentForm.ResetImage(this.imgEdited == null ? this.imgOriginal : this.imgEdited);
            }
            catch (Exception img_Ex)
            {
                Logger.LogException(img_Ex);
                MessageBox.Show("Error, closing");
            }
        }
    }
}
